package com.example.demo.spring.config;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * 子容器配置（注册 Controller、ViewResolver、HandlerMapping）
 */
@ComponentScan(value = "com.example.demo", useDefaultFilters = false,
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, ControllerAdvice.class, RestControllerAdvice.class})}
)
@Configuration //最好标注上，本人亲测若不标准，可能扫描不生效
public class AppConfig {

    @Bean
    public Son son() {
        return new Son();
    }

    @Bean
    public Parent parent() throws Exception {
        Son son = son();
        FactoryBean<Son> sonFactoryBean = sonFactoryBean();
        Son son1 = sonFactoryBean.getObject();
        Son son2 = sonFactoryBean.getObject();
        System.out.println("son1 is equals son2 ?: " + (son1 == son2));
        return new Parent().addSon(son).addSon(son1).addSon(son2);
    }

    @Bean
    public FactoryBean<Son> sonFactoryBean() {
        return new SonFactoryBean();
    }

    class Son {

    }

    class Parent {
        List<Son> sons = new ArrayList<>(12);

        Parent addSon(Son son) {
            sons.add(son);
            return this;
        }
    }

    public class SonFactoryBean implements FactoryBean<Son> {
        @Override
        public Son getObject() throws Exception {
            return new Son();
        }

        @Override
        public Class<?> getObjectType() {
            return Son.class;
        }
    }

}